package com.sky.myapplication.kotlin.kotlinActivity

import android.Manifest
import android.content.Intent
import android.os.Bundle
import android.os.Environment
import android.util.Log
import androidx.appcompat.app.AppCompatActivity
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.blankj.utilcode.util.ToastUtils
import com.sky.myapplication.R
import com.sky.myapplication.java.data.FileEntity
import com.sky.myapplication.java.utils.FileUtils
import com.sky.myapplication.kotlin.kotlinAdapter.FileAdapter
import pub.devrel.easypermissions.EasyPermissions
import java.io.File
import java.util.*

/**
 * Created by Min
 * Date 2023/1/16  9:52
 */
class FileManagerKotlinActivity : AppCompatActivity() {
    lateinit var rv_file_list : RecyclerView
    lateinit var adapter : FileAdapter
    var dataList = ArrayList<FileEntity>()

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_file_manager)

        rv_file_list = findViewById(R.id.rv_file_list)
        rv_file_list.layoutManager = LinearLayoutManager(this)
        adapter = FileAdapter(this, dataList)
        adapter.setFileAdapterClick(object : FileAdapter.FileAdapterClick{
            override fun itemClick(entity: FileEntity) {
                if (entity.directory){
                    val intent = Intent(this@FileManagerKotlinActivity, FileSecondManagerKotlinActivity::class.java)
                    intent.putExtra("path", entity.path)
                    startActivity(intent)
                } else {
                    FileUtils.openFile(this@FileManagerKotlinActivity, entity.path)
                    var intent = FileUtils.openFile(this@FileManagerKotlinActivity, entity.path)
                    if (intent != null)
                        startActivity(intent)

//                    val data = FileProvider.getUriForFile(baseContext, "myprovider",  File(entity.path));
//                    baseContext.grantUriPermission(baseContext.getPackageName(), data, Intent.FLAG_GRANT_READ_URI_PERMISSION);
//                    val intent = Intent(Intent.ACTION_VIEW)
//                        .setDataAndType(data, "video/*")
//                        .addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
//                    startActivity(intent);
//                    try {
//                        var uri: Uri? = null
//                        var file = File(entity.path)
//                        uri = if (Build.VERSION.SDK_INT >= 24) {
//                            val builder = VmPolicy.Builder()
//                            StrictMode.setVmPolicy(builder.build())
//                            Uri.fromFile(file)
//                        } else {
//                            Uri.fromFile(file)
//                        }
//                        val intent = Intent(Intent.ACTION_VIEW)
//                        intent.addCategory(Intent.CATEGORY_DEFAULT)
//                        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)
//                        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
//                        intent.setDataAndType(uri, "image/*")
//                        startActivity(intent)
//                    } catch (e: Exception) {
//                        e.printStackTrace()
//                    }
                }
            }
        })
        rv_file_list.adapter = adapter

        initFileList()
    }

    private fun initFileList(){
//        mStorageManager = getSystemService(Context.STORAGE_SERVICE) as StorageManager
//        var permissions = arrayOf(Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE)
//        var requestCode : Int = 123
//            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
//                if(ActivityCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_DENIED){
//                    ActivityCompat.requestPermissions(this, PERMISSIONS, requestCode)
//                }
//
////                var volumesList : List<StorageVolume> = mStorageManager.getStorageVolumes()
////                for (volume in volumesList){
////                    ToastUtils.showShort(volume.getDescription(this))
////                    var file = volume.directory
////                    Log.i("", file?.path.toString())
////                }
//            }

//            var file = Environment.getDataDirectory()
//            var file = File(Environment.getExternalStorageDirectory().getAbsolutePath())



//            if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT){
//                var files = getExternalFilesDirs(Environment.MEDIA_MOUNTED)
//                for (file in files){
//                    Log.i("min", file.path)
//                }
//            }

//            var file = Environment.getExternalStorageDirectory()
//            var fileList = file.listFiles()
//            for (f in fileList){
//                Log.i("", f.name)
//            }

        dataList.clear()
        if (EasyPermissions.hasPermissions(this, Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE)){
            getFileList()
        } else {
            EasyPermissions.requestPermissions(this, "", 123, Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE);
        }
    }

    fun getFileList(){
        try {
            val path = Environment.getExternalStorageDirectory().getAbsolutePath()
            val file = File(path)
            val fileList = file.listFiles()

            val directoryList = ArrayList<FileEntity>()
            val sourceList = ArrayList<FileEntity>()

            for (f in fileList){
                var file = FileEntity(f.name,
                    f.path,
                    f.isDirectory)
                if (f.isDirectory){
                    directoryList.add(file)
                } else{
                    sourceList.add(file)
                }
            }

            var comparator = object : Comparator<FileEntity>{
                override fun compare(p0: FileEntity?, p1: FileEntity?): Int {
                    return p0!!.name!!.compareTo(p1!!.name)!!
                }
            }
            Collections.sort(directoryList, comparator)
            Collections.sort(sourceList, comparator)

//            dataList.addAll(directoryList)
            dataList.addAll(sourceList)
        } catch (e : java.lang.Exception){

        }
//                dataList.addAll(list.sortedWith(compareBy({it.name})) as ArrayList<FileEntity>)
        rv_file_list.adapter?.notifyDataSetChanged()
    }

    override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<out String>, grantResults: IntArray) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults)
        Log.i("mxp", "onRequestPermissionsResult")
        if(requestCode == 123){
            if (EasyPermissions.hasPermissions(this, Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE)){
                getFileList()
            } else {
                ToastUtils.showShort("请先授权")
            }
        }
    }
}